from rest_framework.views import APIView
from rest_framework.response import Response
from django_redis import get_redis_connection
from rest_framework.permissions import IsAuthenticated
from goods.models import SKU
from carts.serializers import CartSKUSerializer
from .serializers import OrderSaveSerializer
from rest_framework.generics import CreateAPIView

class OrderSettlementView(APIView):
    # 判断用户是否登录
    permission_classes = [IsAuthenticated]

    def get(self, request):
        # 从redis中获取选中的商品
        redis_cli = get_redis_connection('cart')
        # 获取商品的编号和数量
        cart_dict = redis_cli.hgetall('cart%d' % request.user.id)
        print(cart_dict)
        cart_dict1 = {}
        for k, v in cart_dict.items():
            cart_dict1[int(k)] = int(v)
        print(cart_dict1)
        # 获取选中的商品
        cart_selected = redis_cli.smembers('cart_selected%d' % request.user.id)
        # 查询商品数据
        skus = SKU.objects.filter(pk__in=cart_selected)
        for sku in skus:
            sku.count = cart_dict1.get(sku.id)
            sku.selected = True

        serializer = CartSKUSerializer(skus, many=True)
        response = {
            'freight': 10,
            'skus': serializer.data
        }

        # 返回响应的数据
        return Response(response)

class OrderSaveView(CreateAPIView):
    permission_classes = [IsAuthenticated]
    serializer_class = OrderSaveSerializer




